package org.iqiyi.swagger;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean("exampleDocket")
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(this.securitySchemes())
                .securityContexts(this.securityContexts())
                .protocols(CollectionUtil.newHashSet("https", "http"));
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("模仿爱奇艺")
                .description("爱奇艺")
                .version("1.0")
                .build();
    }

    /**
     *
     * @return
     */

    protected List<ApiKey> securitySchemes(){
        List<ApiKey> list = new ArrayList();
        list.add(new ApiKey("用户令牌", "Authorization", "header"));
        return list;

    }

    protected List<SecurityContext> securityContexts(){
        List<SecurityContext> list = new ArrayList();
        SecurityContext sc = SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("^(?!auth).*$")).build();
        list.add(sc);
        return list;

    }

    protected List<SecurityReference> defaultAuth() {
        AuthorizationScope[] globalScope = new AuthorizationScope[1];
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "全局请求头");
        globalScope[0] = authorizationScope;
        List<SecurityReference> list = new ArrayList();

        SecurityReference sv = new SecurityReference("用户令牌", globalScope);

        list.add(sv);
        return list;
    }
}